//
//  UserProfileViewController.m
//  XPhoto
//
//  Created by sentinel on 2020/3/20.
//  Copyright © 2020 baboy. All rights reserved.
//

#import "UserProfileViewController.h"

#import "Post.h"
#import "PhotoTableViewCell.h"
#import "FollowViewController.h"
#import "BKCollectionViewLayout.h"
#import "PhotoCollectionViewCell.h"
#import "PostDetailViewController.h"
//#import "UICollectionView+x.h"
#import "CommonAttributedString.h"
#import "UIScrollView+x.h"
#import "SerialTableViewCell.h"

#import <BKKit/Theme.h>
#import <BKKit/UIButton+x.h>
#import <AFNetworking/UIButton+AFNetworking.h>
#import <AFNetworking/UIImageView+AFNetworking.h>
#import "UIViewController+Link.h"
#import "SerialEditViewController.h"
#import "BKActionSheet.h"

#define PHOTO_COLLECTION_CELL_REUSE_ID @"PhotoCollectionViewCell"
#define POST_SEARCH_PAGE_SIZE   30

@interface UserProfileViewController ()<BKCollectionViewLayoutDelegate, UICollectionViewDelegate, UICollectionViewDataSource,PhotoCollectionViewCellDelegate, BKScrollViewDragRefreshDelegate, UITextViewDelegate, UITableViewDelegate, UITableViewDataSource, BKActionSheetDelegate>
@property(nonatomic, strong) BKCollectionViewLayout *collectionViewLayout;
@property(nonatomic, strong) NSMutableArray *posts;
@property(nonatomic, strong) NSMutableArray *postSerials;
@property(nonatomic, assign) CGFloat navBarHeight;
@property(nonatomic, assign) CGFloat sectionBarOriginOffsetY;

@end

@implementation UserProfileViewController
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [self.postCollectionView removeObserver:self forKeyPath:@"contentSize"];
    [self.serialTableView removeObserver:self forKeyPath:@"contentSize"];
}
- (id)init{
    if (self = [self initWithNibName:NSStringFromClass([self class]) bundle:nil]){
        
    }
    return self;
}
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if (self = [super initWithNibName:nibNameOrNil bundle:nil]){
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userProfileUpdated:) name:NOTIFICATION_USER_PROFILT_UPDATED object:nil];
        self.user = [User currentUser];
        
    }
    return self;
}
- (BKCollectionViewLayout *)collectionViewLayout{
    if (!_collectionViewLayout) {
        _collectionViewLayout = [[BKCollectionViewLayout alloc] init];
        _collectionViewLayout.layoutMode = BKCollectionViewLayoutModeFixedWidthHeight;
        _collectionViewLayout.numberOfColumns = 3;
        _collectionViewLayout.delegate = self;
    }
    return _collectionViewLayout;
}
- (UIScrollView *)currentContentView{
    if (self.postButton.selected) {
        return self.postCollectionView;
    }
    return self.serialTableView;
}
- (BOOL)canGoBack{
    id nav = self.navigationController;
    while (nav != [nav navigationController] && [nav navigationController]) {
        nav = [nav navigationController];
    }
    return [[nav viewControllers] count] > 1;
}
#pragma Listener
- (void)userProfileUpdated:(NSNotification *)noti{
    self.user = [User currentUser];
    [self updateUserProfile];
    
}
- (void)updateUserProfile{
    self.nameLabel.text = self.user.nickname;
    self.userNameLabel.text = [NSString stringWithFormat:@"@%@", self.user.userName];
    self.navBarTitleLabel.text = self.userNameLabel.text;
    if (self.user.cover) {
        [self.coverImageView setImageWithURL:[NSURL URLWithString:self.user.cover]];
    }
    
    NSString *intro = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"intro", @"标签"), self.user.intro?:NSLocalizedString(@"nothing", @"无")];
    self.introlTextView.attributedText = [CommonAttributedString contentAttributedStringWithText:intro];
    
    [self.avatarButton setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:self.user.avatarThumb?:self.user.avatar]];
    [self.postCountButton setTitle:[NSString stringWithFormat:@"%ld", self.user.postCount] forState:UIControlStateNormal];
    [self.fanCountButton setTitle:[NSString stringWithFormat:@"%ld", self.user.fanCount] forState:UIControlStateNormal];
    [self.followCountButton setTitle:[NSString stringWithFormat:@"%ld", self.user.followCount]  forState:UIControlStateNormal];
    
    CGFloat introViewWidth = self.introlTextView.bounds.size.width - self.introlTextView.textContainerInset.left - self.introlTextView.textContainerInset.right - self.introlTextView.textContainer.lineFragmentPadding*2;
    CGRect introViewBounds = [self.introlTextView.attributedText boundingRectWithSize:CGSizeMake(introViewWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
    self.topViewHeightConstraint.constant = self.introlTextView.frame.origin.y + introViewBounds.size.height + self.introlTextView.textContainerInset.top + self.introlTextView.textContainerInset.bottom + self.postButton.bounds.size.height;
    [self updateSectionBarPosition];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    UIView *currentContentView = [self currentContentView] ;
    if ( object == currentContentView && [keyPath isEqualToString:@"contentSize"]) {
        [self contentSizeChanged:object];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.edgesForExtendedLayout = UIRectEdgeAll;
//    self.navigationController.navigationBar.translucent = YES;
//    self.automaticallyAdjustsScrollViewInsets = YES;
    self.navigationController.navigationBar.hidden = YES;
    
    
    self.backButton.hidden = ![self canGoBack];
    DLOG(@"%@,%@,%d", NSStringFromUIEdgeInsets(self.introlTextView.textContainerInset), NSStringFromCGSize(self.contentScrollView.contentSize), [self canGoBack]);
    self.introlTextView.textContainerInset = UIEdgeInsetsMake(10, 0, 10, 0);
    self.serialTableView.tableFooterView = [UIView new];
    [self updateUserProfile];
    [self.postCollectionView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew  context:nil];
    [self.serialTableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew  context:nil];

    self.postCollectionView.backgroundColor = THEME_VIEW_BG_COLOR;
    self.postCollectionView.collectionViewLayout = self.collectionViewLayout;
    UINib *postNib = [UINib nibWithNibName:NSStringFromClass([PhotoCollectionViewCell class]) bundle:nil];
    [self.postCollectionView registerNib:postNib forCellWithReuseIdentifier:PHOTO_COLLECTION_CELL_REUSE_ID];
    
    [self searchWithOffset:0];
    [self searchPostSerialWithOffset:0];
}

- (void)resizeCoverImageView{
    CGFloat coverHeight = self.introlTextView.frame.origin.y;
    CGFloat coverImageViewHeight = coverHeight -self.scrollView.contentOffset.y + self.view.safeAreaInsets.top;
    DLOG(@"safeAreaInsets:%@,%@,%f", NSStringFromUIEdgeInsets(self.view.safeAreaInsets), NSStringFromUIEdgeInsets(self.scrollView.safeAreaInsets),coverImageViewHeight );
    CGRect coverImageViewFrame = self.coverImageView.frame;
    coverImageViewHeight = MAX(coverImageViewHeight, coverHeight/3);
    if (coverImageViewHeight != coverImageViewFrame.size.height) {
        coverImageViewFrame.origin.y = self.scrollView.contentOffset.y - self.view.safeAreaInsets.top;
        coverImageViewFrame.size.height = coverImageViewHeight;
//        DLOG(@"resizeCoverImageView:%@", NSStringFromCGRect(coverImageViewFrame));
        self.coverImageView.frame = coverImageViewFrame;
    }
//    DLOG(@"coverImageFrame:%@,%@", NSStringFromCGRect(self.coverImageView.frame), NSStringFromCGRect(self.coverImageView.bounds));
}
- (void)viewSafeAreaInsetsDidChange{
    [super viewSafeAreaInsetsDidChange];
    [self resizeCoverImageView];
    [self updateSectionBarPosition];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self resizeCoverImageView];
//    [self updateSectionBarPosition];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}
#pragma mark - contentSize observer
- (CGFloat)navBarHeight{
    return self.navBar.bounds.size.height - self.view.safeAreaInsets.top;
}
- (CGFloat)sectionBarOriginOffsetY{
    return self.topViewHeightConstraint.constant;
//    return self.contentScrollView.frame.origin.y - self.sectionBar.bounds.size.height;
}
- (void)updateSectionBarPosition{
    DLOG(@"updateSectionBarPosition:%@,%@", NSStringFromCGPoint(self.scrollView.contentOffset), NSStringFromUIEdgeInsets(self.scrollView.safeAreaInsets));
    CGFloat minOffsetY = 0;
    if([self canGoBack]){
        
    }
    minOffsetY = self.navBar.bounds.size.height - self.view.safeAreaInsets.top;
    CGFloat sectionBarOffsetY = MAX(self.sectionBarOriginOffsetY + self.scrollView.safeAreaInsets.top - self.scrollView.contentOffset.y+ self.scrollView.contentInset.top, minOffsetY);
    self.sectionBarOffsetYConstraint.constant = sectionBarOffsetY;
}
- (void)contentSizeChanged:(UIScrollView *)scrollView{
    CGFloat contentScrollViewMaxHeight = self.scrollView.bounds.size.height - self.navBarHeight - self.sectionBar.bounds.size.height ;
    CGRect frame = self.contentScrollView.frame;
    CGFloat h = MAX(scrollView.contentSize.height, self.scrollView.bounds.size.height - frame.origin.y);
    h = MIN(contentScrollViewMaxHeight, scrollView.contentSize.height);
    if (h > frame.size.height) {
        DLOG(@"%f,%f,%@", frame.size.height,h, NSStringFromUIEdgeInsets(self.view.safeAreaInsets));
        frame.size.height = h;
        self.contentScrollViewHeightConstraint.constant = h;
        self.contentScrollView.contentSize = CGSizeMake(frame.size.width * 2, h);
        self.scrollView.contentSize = CGSizeMake(self.scrollView.bounds.size.width, frame.origin.y + h);
    }
}
- (void)searchWithOffset:(NSInteger)offset{
    PostSearchArgs *args = [PostSearchArgs new];
    args.uid = @(self.user.uid);
    args.offset = offset;
    args.pageSize = POST_SEARCH_PAGE_SIZE;
    [Post searchWithArgs:args
                callback:^(id  task, id  posts, NSError * _Nonnull error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
        }
        if (posts && [posts count] > 0) {
            if (offset == 0) {
               self.posts = [NSMutableArray array];
            }
            [self.postCollectionView removeEmptyIndicator];
            [self.posts addObjectsFromArray:posts];
            [self.postCollectionView reloadData];
            self.postCollectionView.loadMore = [posts count] == POST_SEARCH_PAGE_SIZE;
        }
        [self.postCollectionView stopLoading];
        if (self.posts.count == 0) {
            [self.postCollectionView showEmptyMsg:NSLocalizedString(@"no_request_data", @"提示数据")
                                             icon:nil
                                       withTarget:nil
                                       withAction:nil];
        }
    }];
}
#pragma mark - BKScrollViewDragRefreshDelegate
- (void)scrollViewWillBeginLoadingMore:(id)scrollView{
    if (scrollView == self.postCollectionView) {
        [self searchWithOffset:self.posts.count];
    }
    if (scrollView == self.serialTableView) {
        [self searchPostSerialWithOffset:self.postSerials.count];
    }
}
#pragma mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.posts.count;
}
/**
 * 元素高度
 */
- (CGFloat) collectionViewLayout:(id)layout heightForItemInSection:(NSInteger)section{
    CGFloat h = 128;
    return h;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: PHOTO_COLLECTION_CELL_REUSE_ID forIndexPath:indexPath];
    cell.delegate = self;
    Post *post = [self.posts objectAtIndex:indexPath.item];
    cell.backgroundColor = [UIColor grayColor];
    cell.post = post;
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    PhotoCollectionViewCell *cell = (PhotoCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    PostDetailViewController *vc = [[PostDetailViewController alloc] init];
    vc.post = cell.post;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma  mark - PhotoCollectionViewCell Delegate
- (void)photoCollectionViewCellDidClicked:(PhotoCollectionViewCell *)cell{
    Post *post = cell.post;
    PostDetailViewController *vc = [[PostDetailViewController alloc] init];
    vc.post = post;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma serialTableView
- (void)searchPostSerialWithOffset:(NSInteger)offset{
    PostSerialSearchArgs *searchArgs = [PostSerialSearchArgs new];
    searchArgs.offset = offset;
    searchArgs.uid = @(self.user.uid);
    [PostSerial search:searchArgs
          withCallback:^(id  _Nonnull task, NSArray*  _Nullable arr, NSError * _Nullable error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
        }
        if (arr && [arr count] > 0) {
            if(offset == 0){
                self.postSerials = [NSMutableArray array];
            }
            [self.postSerials addObjectsFromArray:arr];
            [self.serialTableView removeEmptyIndicator];
            [self.serialTableView reloadData];
        }
        //没有请求到数据并且之前也没有数据
        if ( self.postSerials.count == 0 ) {
            [self.serialTableView showEmptyMsg:NSLocalizedString(@"no_request_data", nil)
                                          icon:nil
                                    withTarget:nil
                                    withAction:nil];
        }
        [self.serialTableView stopLoading];
        self.serialTableView.loadMore = arr && arr.count == searchArgs.pageSize;
        
    }];
}
- (SerialTableViewCell *)serialTableViewCell{
    SerialTableViewCell *cell = [self.serialTableView dequeueReusableCellWithIdentifier: SERIAL_TABLE_VIEW_CELL_REUSE_ID];
    if (!cell) {
        cell = loadViewFromNib([SerialTableViewCell class], self);
//        cell.delegate = self;
    }
    return cell;
}
#pragma mark - UITableViewDelegate Serial Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger n = self.postSerials? self.postSerials.count : 0;
    return n;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    PostSerial *postSerial = [self.postSerials objectAtIndex:indexPath.row];
    CGFloat h = [[self serialTableViewCell] heightWithPostSerial:postSerial width:tableView.bounds.size.width];
    return h;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PostSerial *postSerial = [self.postSerials objectAtIndex:indexPath.row];
    SerialTableViewCell *cell = [self serialTableViewCell];
    cell.postSerial = postSerial;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    PostSerial *postSerial = [self.postSerials objectAtIndex:indexPath.row];
    SerialEditViewController *vc = [[SerialEditViewController alloc] init];
    vc.postSerial = postSerial;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - UISCrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.contentScrollView) {
        NSInteger i = (scrollView.contentOffset.x + scrollView.bounds.size.width/2)/scrollView.bounds.size.width;
        [self sectionBarStatusChangedWithButtonSelected:(i == 0 ? self.postButton : self.serialButton)];
        return;
    }
    if(scrollView == self.postCollectionView ||
       scrollView == self.serialTableView){
        CGFloat thresholdHeight = self.sectionBarOriginOffsetY - self.navBarHeight;
        //在阈值以内，滚动子tableView需要转化到父view的滚动
        CGFloat superOffsetY = MIN( scrollView.contentOffset.y + self.scrollView.contentOffset.y, thresholdHeight);
        
        CGFloat subOffsetY = scrollView.contentOffset.y + self.scrollView.contentOffset.y - superOffsetY;
        DLOG(@"=======%f,%f,%f", superOffsetY, subOffsetY, scrollView.contentOffset.y);
        [self.scrollView setContentOffset:CGPointMake(0, superOffsetY)];
        if(subOffsetY != scrollView.contentOffset.y){
            [scrollView setContentOffset:CGPointMake(0, subOffsetY)];
        }
        [scrollView scrollViewDidScroll];
    }
    
    CGFloat navBarHeight =  (self.navBar.bounds.size.height - self.view.safeAreaInsets.top);
    CGFloat alpha = 1 - (self.sectionBarOffsetYConstraint.constant - navBarHeight)/navBarHeight;
    alpha = MIN(alpha, 0.98);
    self.navBar.alpha = alpha;
    
    [self resizeCoverImageView];
    [self updateSectionBarPosition];
}
 

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    //处理因子视图向下拖拽而导致父视图无法回到原位置
    if(scrollView == self.postCollectionView ||
       scrollView == self.serialTableView){
        CGFloat offsetY = self.scrollView.contentOffset.y;
        if (offsetY < 0) {
            [self.scrollView setContentOffset:CGPointZero animated:YES];
        }
        if (self.scrollView.contentOffset.y > (self.scrollView.contentSize.height - self.scrollView.bounds.size.height)) {
            [self.scrollView setContentOffset:CGPointMake(0, self.scrollView.contentSize.height - self.scrollView.bounds.size.height) animated:YES];
        }
        [scrollView scrollViewDidEndDragging];
    }
}
//- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
//}
#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction{
    DLOG(@"URL:%@",URL);
    return [self openLink:URL];
    return YES;
}
#pragma mark - click event

- (IBAction)changeAvatar:(id)sender{
}
- (IBAction)clickRecordButton:(id)sender{
}
- (IBAction)clickFanButton:(id)sender{
    FollowViewController *vc = [[FollowViewController alloc]  init];
    vc.uid = self.user.uid;
    vc.selectedIndex = 1;
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)clickFollowButton:(id)sender{
    FollowViewController *vc = [[FollowViewController alloc]  init];
    vc.uid = self.user.uid;
    vc.selectedIndex = 0;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)editProfile:(id)sender{
}
- (IBAction)clickSettingButton:(id)sender{
}
#pragma mark - section bar change event
- (void)sectionBarStatusChangedWithButtonSelected:(UIButton *)button{
    if (button.selected) {
        return;
    }
    self.postButton.selected = self.postButton == button;
    self.serialButton.selected = self.serialButton == button;
}
- (IBAction)clickPostButton:(UIButton *)button{
    if (button.selected) {
        return;
    }
    [self sectionBarStatusChangedWithButtonSelected:button];
    
    [self.serialTableView setContentOffset:CGPointMake(0, 0) animated:NO];
    CGPoint p = CGPointMake(0, 0);
    [self.contentScrollView setContentOffset:p animated:YES];
}
- (IBAction)clickSerialButton:(UIButton *)button{
    if (button.selected) {
        return;
    }
    [self sectionBarStatusChangedWithButtonSelected:button];
    
    [self.serialTableView setContentOffset:CGPointMake(0, 0) animated:NO];
    CGPoint p = CGPointMake(self.contentScrollView.bounds.size.width, 0);
    [self.contentScrollView setContentOffset:p animated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

